package dgut.party.business.common.util;

import lombok.Getter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
@Log4j2
@Getter
public class FileService {

  @Value("${spring.servlet.multipart.location}")
  private String uploadRoot;

  private String makeFloderDirectory(String floderPath) {
    if (!floderPath.startsWith(this.uploadRoot)) {
      System.err.println("非项目文件路径！");
      return null;
    }
    File directory = new File(floderPath);
    if (!directory.exists()) {
      directory.mkdirs();
    }
    return floderPath;
  }

  public ResponseEntity<byte[]> downloadFile(String filePath) throws IOException {
    File file = new File(filePath);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    try {
      return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    } catch (IOException e) {
      log.error("文件下载异常：：" + e.getMessage());
      throw e;
    }
  }

  public String uploadFile(String filePath, MultipartFile file) throws IOException {

    makeFloderDirectory(filePath);
    String fileName = "";
    if (!filePath.endsWith("/")) {
      fileName = filePath.substring(filePath.lastIndexOf('/') + 1,
        filePath.contains(".") ? filePath.lastIndexOf(".") : filePath.length());
    } else {
      fileName = file.getName();
    }
    fileName = fileName + "-" + UUID.randomUUID().toString().substring(0, 10);
    file.transferTo(new File(filePath + fileName));
    return fileName;

  }
}
